import { WeComponent } from '../../framework/common/component';

const util = require('../../utils/util.js')
const api = require('../../config/api.js')
import Dialog from '../../vendors/vant-weapp/dialog/dialog'
const App = getApp()
const DATA_KEY = 'shop-cart'

WeComponent({
  name: 'shopCart',

  //用于接收外部传递的参数
  props: {
     
  },
  data: {
    
    evtChange: 'productchange',
    cartCreated: 'cartcreated',
    evtPopup: 'onpopup',
    evtOpts: {},

    productList: [],

    shopCartShow: false,
    
    // 删除按钮宽度单位（rpx）
    delBtnWidth: 160
  },
  computed: {

    // 价格计算(单价 x 数量 x 天数)
    amountOfMoney() {
      let vm = this
      let total = 0

      if(!util.isEmpty(vm.data.productList)){
        vm.data.productList.forEach(one => {
          let price = one.price
          if(!util.isNumber(price)){
            price = 0 
          }
          // 元转分
          price = price * 100

          let count = one.count
          if(!util.isNumber(count)){
            count = 0 
          }
          total += price * count
        })
        return total
      }else{
        return 0
      }
    },
    submitDisabled(){
      let vm = this
      return util.isEmpty(vm.data.productList)
    },

    // 计算购物车商品数量
    productCount(){
      let vm = this
    
      let count = 0
      if(!util.isEmpty(vm.data.productList)){
        vm.data.productList.forEach(one => {
          if (!one.count) {
            one.count = 1
          }
          count += one.count
        })
      }
      return count
    }
  },
  created:function () {
    let vm = this
    let prodLst = vm.getStorageProducts()
    vm.setData({
      productList: prodLst
    })
    console.log('shop-cart attached 商品数:' + vm.data.productList.length)

    // triggerEvent
    const evtDetail = {
      productList: prodLst
    }
    vm.triggerEvent(vm.data.cartCreated, evtDetail, vm.data.evtOpts)
  },
  destroyed() {
    let vm = this
    console.log('shop-cart detached')
    vm.updateStorageProducts(vm.data.productList)
  },
  //方法列表
  methods: {
    // 从缓存获取商品信息
    getStorageProducts(){
      let prodList = util.getStorageSync(DATA_KEY)
      if(!util.isEmpty(prodList)){
        return prodList
      }
      return []
    },

    // 更新缓存中的商品信息
    updateStorageProducts(products) {
      if(products){
        wx.setStorageSync(DATA_KEY, products)
      }else{
        wx.removeStorageSync(DATA_KEY)
      }
    },

    // 提交订单
    submit(){
      let vm = this
      let proLst = vm.data.productList
      if(!util.isEmpty(proLst)){
        let chargeItems = proLst.map((one) => {
          let item = {}
          item.orgId = one.id
          item.itemName = one.title
          item.itemImage = one.cover
          item.price = one.price
          item.amount = one.count
          return item
        })
        Dialog.confirm({
          // 在组件中使用的时候，如果不指定context则会报错
          context: vm,
          title: '提示',
          message: '确认提交吗?'
        })
        .then(() => {
          // 点击确认
          wx.showLoading({
            mask: true
          })

          let data = {
            'itemList': chargeItems
          }
          let jsonData = JSON.stringify(data)
          
          util.wxRequest({
            url: api.Delicacy_submitOrder,
            method: 'post',
            header: {
              'content-type': 'application/json;charset=UTF-8'
            },
            data: jsonData,
            success: function (obj) {
              let ret = obj.data
              if(ret.status === '200'){
                // 清空购物车
                vm.setData({
                  productList:[]
                })
                vm.updateStorageProducts([])

                wx.showToast({
                  title: '提交成功',
                  icon: 'success',
                  duration: 2000,
                  complete: () => {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/pages/qianbao/qianbao'
                      })
                    }, 1500)
                  }
                })
              }else{
                util.showToast(ret.message)
              }
            },
            complete: function () {
              wx.hideLoading()
            }
          })
          
        })
        .catch((e) => {
          // dialog on cancel
          console.log('dialog on cancel')
          console.log(e)
          wx.hideLoading()
        })
        
      }else{
        // 购物车为空，没啥好提交的
        console.log('购物车为空，没啥好提交的')
      }
    },

    // 添加商品
    addProduct(product){
      let vm = this
      if(!util.isEmpty(product) && product.id){
        let exist = false
        let prodList = vm.data.productList

        // 如果已经存在则count+1
        prodList.forEach((one,index) => {
          let _id = one.id
          if(_id === product.id){
            exist = true
            if (!one.count) {
              one.count = 0
            }
            let count = one.count
            count += 1
            
            let key = "productList[" + index + "].count"
            vm.setData({
              [key]: count
            })

            product.count = count
          }
        })
        if(!exist){
          // 不存在则count=1，push
          if (!product.count) {
            product.count = 1
          }
          prodList.push(product)
          vm.setData({
            productList: prodList
          })
        }
        
        // triggerEvent
        const evtDetail = {
          product: product
        }
        vm.triggerEvent(vm.data.evtChange, evtDetail, vm.data.evtOpts)
      }else{
        // donothing
        console.log('商品不能为空,且商品必须存在id')
      }
    },

    onShopCartShow(){
      let vm = this
      vm.setData({
        shopCartShow: true
      })
      // triggerEvent
      const evtDetail = {
        popup: true
      }
      vm.triggerEvent(vm.data.evtPopup, evtDetail, vm.data.evtOpts) 
    },
  
    onShopCartClose(){
      let vm = this
      vm.setData({
        shopCartShow: false
      })
      // triggerEvent
      const evtDetail = {
        popup: false
      }
      vm.triggerEvent(vm.data.evtPopup, evtDetail, vm.data.evtOpts) 
    },

    // 数量变化处理
    onCountChange(event){
      let page = this
      let count = event.detail
      let item = event.target.dataset.item
      
      let arr = page.data.productList
      arr.forEach((el, index) =>{
        if(item.id === el.id) {
          let key = "productList[" + index + "].count"
          page.setData({
            [key]: count
          })
        }
      })

      // triggerEvent
      item.count = count
      const evtDetail = {
        product: item
      }
      page.triggerEvent(page.data.evtChange, evtDetail, page.data.evtOpts)
    },

    // 左滑
    // 手指触摸动作开始 记录起点X坐标
    touchstart: function (e) {
      //console.log('touchstart')
      // 开始触摸时 重置所有删除 _touchstart是touch里面的函数方法
      let data = App.touch._touchstart(e, this.data.productList)
      //console.log(data)

      this.setData({
        productList: data
      })
    },

    // 滑动事件处理 手指触摸后移动的事件 这里会把数组里的isTouchMove改为true，其它改为false
    touchmove: function (e) {
      //console.log('touchmove')
      // .touchmove是touch里面的函数方法
      let data = App.touch._touchmove(e, this.data.productList)
      //console.log(data)
      
      this.setData({
        productList: data
      })
    },

    // 删除事件
    del: function (event) {
      let vm = this
      let index = event.target.dataset.index
      let arr = vm.data.productList

      let product = arr[index]
      
      arr.splice(index,1)
      vm.setData({
        productList: arr
      })

      // triggerEvent
      product.count = 0
      const evtDetail = {
        product: product
      }
      vm.triggerEvent(vm.data.evtChange, evtDetail, vm.data.evtOpts)
    }
  }
})